<?php
/**
 * User: Tegic
 * Date: 2018/6/5
 * Time: 10:42
 */

namespace app\repositories;


use app\common\model\Profile;
use app\common\model\User;
use think\Db;

class UserRepository
{
	/**
	 * @Function update
	 *
	 * @param $id
	 * @param $data
	 *
	 * @return bool|string
	 * @Author   tegic
	 * @Time     2018/6/5 10:45
	 */
	static public function update($id, $data)
	{
		try {
			( new User() )->allowField(true)->where('id', $id)->update($data);
		} catch (\Exception $e) {
			return $e->getMessage();
		}
		return true;
	}
	
	/**
	 * 注册
	 * @Function register
	 *
	 * @param $data
	 *
	 * @return string
	 * @Author   tegic
	 * @Time     2018/6/5 10:45
	 */
	static public function register($data)
	{
		$user                             = new User();
		$data[$data['ostype'] . '_token'] = request()->token;
		$data['password']                 = md5($data['password']);
		Db::startTrans();
		try {
			$user->allowField(true)->save($data);
			$user->profile()->allowField(true)->save([ 'user_id' => $user->id, 'nickname' => env('DEFAULT_NICKNAME_PREFIX', 'nickname') . mt_rand(100, 999) ]);
			Db::commit();
		} catch (\Exception $e) {
			Db::rollback();
			return $e->getMessage();
		}
		$ret = $user->toArray();
		unset($ret['password']);
		cache(request()->tokenPrefix, $ret, config('app.user_overtime'));
		return $ret;
	}
	
	/**
	 * 登录
	 * @Function login
	 *
	 * @param $data
	 *
	 * @return array|null|\PDOStatement|string|\think\Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @Author   tegic
	 * @Time     2018/6/5 10:46
	 */
	static public function login($data)
	{
		$result = User::where('mobile', $data['mobile'])->where('password', md5($data['password']))->find();
		if (!$result) {
			return false;
		}
		self::update($result['id'], [ $data['ostype'] . '_token' => $data['token'], 'activity_time' => time() ]);
		$result = $result->toArray();
		unset($result['password']);
		cache(request()->tokenPrefix, $result, config('app.user_overtime'));
		return $result;
	}
	
	/**
	 * 查找单条数据
	 * @Function find
	 *
	 * @param $id
	 *
	 * @return array|null|\PDOStatement|string|\think\Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @Author   tegic
	 * @Time     2018/6/5 11:16
	 */
	static public function find($id)
	{
		$data = User::cache(true)->find($id);
		if ($data) {
			$data = $data->toArray();
			unset($data['password']);
		}
		return $data;
	}
	
	static public function test()
	{
		$data = User::all();
		$data = $data->toArray();
		var_dump($data);
	}
}